package j.util.pkgenerator;

import j.util.New;
import j.util.StringUtils;

import java.util.Map;

/**
 * 主键生成器，由于引用的地方较多，故该类名字为“PG"
 * User: jason
 * Date: 13-4-19 上午11:16
 */
public class PG {
    private PG(){
        map = New.map();
    }
    private static final PG instance = new PG();

    private boolean inited = false;
    private PkGeneratorService service;
    private Map<String,NextValue> map;

    PkGeneratorService getService(){
        return service;
    }

    public static void init(PkGeneratorService service){
        instance.service = service;
        instance.inited = true;
    }

    public static String getNext(String key){
        return getNext(null,key);
    }
    public static String getNext(String prefix,String key){
        if(!instance.inited){
            throw new RuntimeException("主键生成器还没初始化，请检查系统配置环境。");
        }
        NextValue nextValue = instance.getNextValue(key);
        int next = nextValue.getNext(instance,key);
        if(StringUtils.isNullOrEmpty(prefix)){
            prefix = nextValue.getPrefix();
        }
        return instance.service.generatePrimaryKey(prefix, nextValue.getLength(),nextValue.getDateFormat(),next);
    }

    private NextValue getNextValue(String key){
        NextValue nv = instance.map.get(key);
        if(null == nv){
            synchronized (PG.class){
                nv = instance.map.get(key);
                if(null == nv){
                    nv = instance.service.generateNextValueByKey(key);
                    if(null == nv){
                        throw new RuntimeException(String.format("获取Key为[%s]的主键不存在定义，请与管理员联系。",key));
                    }
                    map.put(key,nv);
                }
            }
        }
        return nv;
    }
}
